﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using VBF = Microsoft.VisualBasic.FileIO;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor
{
    /// <summary>
    /// UnLinkedImagesDialog.xaml 的交互逻辑
    /// </summary>
    public partial class UnLinkedImagesDialog : MetroWindow
    {
        public UnLinkedImagesDialog(List<string> unLinkedImagePathes, List<ImageTitleAndPath> titleInfos)
        {
            InitializeComponent();

            foreach (var ip in unLinkedImagePathes)
            {
                var title = "";
                foreach (var titleInfo in titleInfos)
                {
                    if (titleInfo.ImageFilePath == ip)
                    {
                        title = titleInfo.Title;
                        break;
                    }
                }

                var newItem = new UnlinkedImageListItem(ip, title, imgPreview);
                lbxImageFiles.Items.Add(newItem);
                newItem.PreviewMouseLeftButtonDown += NewItem_PreviewMouseLeftButtonDown;
            }
        }

        private void NewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                var imgPath = (sender as UnlinkedImageListItem)?.FilePath;
                if (System.IO.File.Exists(imgPath))
                {
                    imgPreview.Source = Globals.LoadBitmapImageFromFile(imgPath);
                }
                else
                {
                    LMessageBox.ShowWarning("此图像文件不存在！");
                }
            }
        }

        private void btnSelectAll_Click(object sender, RoutedEventArgs e)
        {
            foreach (var ue in lbxImageFiles.Items)
            {
                var ui = ue as UnlinkedImageListItem;
                if (ui != null)
                    ui.IsChecked = true;
            }
        }

        private void btnSelectSwitch_Click(object sender, RoutedEventArgs e)
        {
            foreach (var ue in lbxImageFiles.Items)
            {
                var ui = ue as UnlinkedImageListItem;
                if (ui != null)
                {
                    if (ui.IsChecked.HasValue && ui.IsChecked.Value == true)
                    {
                        ui.IsChecked = false;
                    }
                    else { ui.IsChecked = true; }
                }
            }
        }

        private void btnUnSelectAll_Click(object sender, RoutedEventArgs e)
        {
            foreach (var ue in lbxImageFiles.Items)
            {
                var ui = ue as UnlinkedImageListItem;
                if (ui != null)
                    ui.IsChecked = false;
            }
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var answer = LMessageBox.Show("要将选中的图像文件都删除到回收站吗？", Globals.AppName,
                      MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (answer != MessageBoxResult.Yes) return;

                // Microsoft.VisualBasic.FileIO 才可以删除到回收站
                foreach (var ue in lbxImageFiles.Items)
                {
                    var ui = ue as UnlinkedImageListItem;
                    if (System.IO.File.Exists(ui.FilePath))
                    {
                        VBF.FileSystem.DeleteFile(ui.FilePath,
                            VBF.UIOption.OnlyErrorDialogs, VBF.RecycleOption.SendToRecycleBin);
                        var wtvi = Globals.MainWindow.FindWorkspaceTreeViewItem(ui.FilePath);
                        if (wtvi != null)
                        {
                            var pwtvi = wtvi.ParentWorkspaceTreeViewItem;
                            if (pwtvi != null)
                                pwtvi.Items.Remove(wtvi);
                        }
                    }
                }

                LMessageBox.ShowInfomation("选中的图像文件已删除到回收站！");
            }
            catch (Exception ex)
            {
                LMessageBox.ShowWarning(ex.Message);
            }
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }

    public class ImageTitleAndPath
    {
        public string Title { get; set; }
        public string ImageFilePath { get; set; }
    }

    public class UnlinkedImageListItem : ListBoxItem
    {
        public UnlinkedImageListItem(string filePath, string title, Image previewImage)
        {
            this.previewImage = previewImage;
            this.Style = this.FindResource("MetroListBoxItem") as Style;

            this.HorizontalAlignment = HorizontalAlignment.Center;
            var grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition());
            grid.RowDefinitions.Add(new RowDefinition());

            if (string.IsNullOrWhiteSpace(title))
            {
                ckx.Content = new FileInfo(filePath).Name;
            }
            else ckx.Content = title;

            grid.Children.Add(ckx);

            this.filePath = filePath;

            var tb = new TextBlock()
            {
                Text = "> " + filePath,
                Margin = textBlockMargin,
                Width = 400,
                TextWrapping = TextWrapping.Wrap,
                Foreground = textColor,
            };
            Grid.SetRow(tb, 1);
            grid.Children.Add(tb);
            this.Content = new Border()
            {
                Child = grid,
                BorderBrush = Brushes.SaddleBrown,
                BorderThickness = new Thickness(0, 0, 0, 1),
                SnapsToDevicePixels = true,
                Padding = padding,
                Margin = marging,
            };

            this.PreviewMouseLeftButtonDown += FileSelectorItem_PreviewMouseLeftButtonDown;
            ckx.Checked += Ckx_Checked;
            ckx.Unchecked += Ckx_Unchecked;
        }

        private Image previewImage;

        private void Ckx_Unchecked(object sender, RoutedEventArgs e)
        {
            this.Background = Brushes.LightGray;
        }

        private void Ckx_Checked(object sender, RoutedEventArgs e)
        {
            this.Background = Brushes.Transparent;
        }

        private static Brush textColor = new SolidColorBrush(new Color() { R = 187, G = 97, B = 21, A = 255, });

        private static Thickness marging = new Thickness(4, 2, 4, 2);

        private static Thickness padding = new Thickness(2);

        private static Thickness textBlockMargin = new Thickness(30, 2, 10, 2);

        private void FileSelectorItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                if (previewImage != null)
                    previewImage.Source = Globals.LoadBitmapImageFromFile(filePath);
            }
            else
            {
                e.Handled = true;
                if (ckx.IsChecked == true)
                {
                    ckx.IsChecked = false;
                }
                else ckx.IsChecked = true;
            }
        }

        private CheckBox ckx = new CheckBox() { Margin = new Thickness(4, 2, 4, 2), IsChecked = true, };

        public bool? IsChecked
        {
            get { return ckx.IsChecked; }
            set { ckx.IsChecked = value; }
        }

        private string filePath = "";

        public string FilePath
        {
            get { return this.filePath; }
        }
    }
}
